const express = require('express');
const router = express.Router();
const Schedule = require('../model/Schedule');
const Technician = require('../model/Technician');
const User = require('../model/model').User;
const Role = require('../model/model').Role;

// 权限检查中间件 - 支持JWT token认证
const checkPermission = (requiredRoles) => {
    return async (req, res, next) => {
        try {
            let user = null;
            
            // JWT密钥
            const JWT_SECRET = 'rbac-system-secret-key';
            
            // 检查token认证
            const token = req.headers['x-auth-token'];
            if (token) {
                try {
                    // 验证JWT token
                    const jwt = require('jsonwebtoken');
                    const decoded = jwt.verify(token, JWT_SECRET);
                    
                    // 从token中获取用户ID
                    const userId = decoded.user?.id || decoded.user?._id;
                    if (userId) {
                        user = await User.findById(userId).populate('role');
                    }
                } catch (error) {
                    console.error('JWT Token验证失败:', error);
                }
            }
            
            // 如果没有token，检查session认证
            if (!user && req.session && req.session.userId) {
                user = await User.findById(req.session.userId).populate('role');
            }
            
            if (!user) {
                return res.status(401).json({ message: '未登录' });
            }

            if (!requiredRoles.includes(user.role.name)) {
                return res.status(403).json({ message: '权限不足' });
            }

            req.user = user;
            next();
        } catch (error) {
            console.error('权限检查错误:', error);
            res.status(500).json({ message: '权限检查失败', error: error.message });
        }
    };
};

// 获取所有员工（技师）列表 - 从User模型中获取角色为"员工"的用户，支持搜索
router.get('/technicians', async (req, res) => {
    try {
        const { search = '', status = 'true' } = req.query;
        
        // 查找员工角色
        const employeeRole = await Role.findOne({ name: '员工' });
        if (!employeeRole) {
            return res.status(404).json({
                success: false,
                message: '未找到员工角色'
            });
        }

        // 构建查询条件
        let query = { 
            role: employeeRole._id
        };

        // 状态筛选
        if (status !== 'all') {
            query.status = status === 'true';
        }

        // 搜索条件
        if (search) {
            const searchRegex = new RegExp(search, 'i');
            query.$or = [
                { username: searchRegex },
                { email: searchRegex },
                { phone: searchRegex }
            ];
        }

        // 获取员工用户，按创建时间降序排序
        const employees = await User.find(query)
            .select('username email phone sex age status createTime')
            .sort({ createTime: -1 });
        
        // 格式化为前端需要的格式
        const formattedEmployees = employees.map(emp => ({
            id: emp._id,
            username: emp.username,
            email: emp.email,
            phone: emp.phone,
            sex: emp.sex,
            age: emp.age,
            status: emp.status,
            createTime: emp.createTime
        }));

        res.json({
            success: true,
            data: formattedEmployees,
            total: formattedEmployees.length
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取员工列表失败',
            error: error.message
        });
    }
});

// 获取排班数据
router.get('/events', async (req, res) => {
    try {
        const { start, end } = req.query;
        
        if (!start || !end) {
            return res.status(400).json({
                success: false,
                message: '请提供开始和结束日期'
            });
        }

        const startDate = new Date(start);
        const endDate = new Date(end);

        const schedules = await Schedule.findByDateRange(startDate, endDate)
            .populate('technician', 'username avatar skills')
            .populate('createdBy', 'username');

        const events = schedules.map(schedule => ({
            id: schedule._id,
            title: schedule.title,
            start: schedule.start,
            end: schedule.end,
            allDay: schedule.allDay,
            color: schedule.color,
            technician: schedule.technician,
            status: schedule.status,
            notes: schedule.notes,
            createdBy: schedule.createdBy?.username || '未知用户',
            createTime: schedule.createTime
        }));
        
        res.json({
            success: true,
            data: events
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取排班数据失败',
            error: error.message
        });
    }
});

// 创建排班
router.post('/events', checkPermission(['老板', '管理员']), async (req, res) => {
    try {
        const { technician, title, start, end, color, notes } = req.body;
        // 验证必填字段
        if (!technician || !start || !end) {
            return res.status(400).json({
                success: false,
                message: '请提供完整的排班信息'
            });
        }

        // 检查时间冲突
        const conflict = await Schedule.checkConflict(technician, new Date(start), new Date(end));
        if (conflict) {
            return res.status(409).json({
                success: false,
                message: '该时间段已有排班'
            });
        }

        const schedule = new Schedule({
            technician,
            title: title || '工作安排',
            start: new Date(start),
            end: new Date(end),
            color: color || '#3788d8',
            notes: notes || '',
            createdBy: req.user._id
        });

        await schedule.save();

        const populatedSchedule = await Schedule.findById(schedule._id)
            .populate('technician', 'username avatar skills')
            .populate('createdBy', 'username');

        res.json({
            success: true,
            data: populatedSchedule,
            message: '排班创建成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '创建排班失败',
            error: error.message
        });
    }
});

// 更新排班
router.put('/events/:id', checkPermission(['老板', '管理员']), async (req, res) => {
    try {
        const { id } = req.params;
        const { technician, title, start, end, color, notes, status } = req.body;

        const schedule = await Schedule.findById(id);
        if (!schedule) {
            return res.status(404).json({
                success: false,
                message: '排班记录不存在'
            });
        }

        // 检查时间冲突（排除当前记录）
        if (start && end && technician) {
            const conflict = await Schedule.checkConflict(
                technician, 
                new Date(start), 
                new Date(end), 
                id
            );
            if (conflict) {
                return res.status(409).json({
                    success: false,
                    message: '该时间段已有排班'
                });
            }
        }

        // 更新字段
        if (technician) schedule.technician = technician;
        if (title) schedule.title = title;
        if (start) schedule.start = new Date(start);
        if (end) schedule.end = new Date(end);
        if (color) schedule.color = color;
        if (notes !== undefined) schedule.notes = notes;
        if (status) schedule.status = status;
        schedule.updatedBy = req.user._id;

        await schedule.save();

        const populatedSchedule = await Schedule.findById(schedule._id)
            .populate('technician', 'username avatar skills')
            .populate('createdBy', 'username')
            .populate('updatedBy', 'username');

        res.json({
            success: true,
            data: populatedSchedule,
            message: '排班更新成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新排班失败',
            error: error.message
        });
    }
});

// 删除排班
router.delete('/events/:id', checkPermission(['老板', '管理员']), async (req, res) => {
    try {
        const { id } = req.params;

        const schedule = await Schedule.findById(id);
        if (!schedule) {
            return res.status(404).json({
                success: false,
                message: '排班记录不存在'
            });
        }

        await Schedule.findByIdAndDelete(id);

        res.json({
            success: true,
            message: '排班删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '删除排班失败',
            error: error.message
        });
    }
});

// 获取资源优化建议
router.get('/optimization-suggestions', async (req, res) => {
    try {
        const { start, end } = req.query;
        
        if (!start || !end) {
            return res.status(400).json({
                success: false,
                message: '请提供开始和结束日期'
            });
        }

        const startDate = new Date(start);
        const endDate = new Date(end);

        // 获取所有员工
        const technicians = await Technician.find({ 
            status: true,
            role: '689dc4e6889e4412b3bdfed2'
        });

        // 获取排班数据
        const schedules = await Schedule.findByDateRange(startDate, endDate)
            .populate('technician', 'username skills');

        // 分析排班情况
        const analysis = {
            totalDays: Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)),
            totalTechnicians: technicians.length,
            schedules: schedules,
            suggestions: []
        };

        // 生成优化建议
        const dateMap = new Map();
        
        schedules.forEach(schedule => {
            const dateKey = schedule.start.toISOString().split('T')[0];
            if (!dateMap.has(dateKey)) {
                dateMap.set(dateKey, []);
            }
            dateMap.get(dateKey).push(schedule.technician);
        });

        // 检查每日排班情况
        for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
            const dateKey = d.toISOString().split('T')[0];
            const scheduledTechs = dateMap.get(dateKey) || [];
            
            if (scheduledTechs.length === 0) {
                analysis.suggestions.push({
                    type: 'warning',
                    date: new Date(d),
                    message: `${dateKey} 无员工排班，建议安排员工上班`
                });
            } else if (scheduledTechs.length < Math.ceil(technicians.length / 2)) {
                analysis.suggestions.push({
                    type: 'info',
                    date: new Date(d),
                    message: `${dateKey} 排班员工较少，可考虑增加人手`
                });
            }
        }

        // 检查员工工作负荷
        technicians.forEach(tech => {
            const techSchedules = schedules.filter(s => s.technician._id.toString() === tech._id.toString());
            const workDays = techSchedules.length;
            
            if (workDays === 0) {
                analysis.suggestions.push({
                    type: 'warning',
                    technician: tech.username,
                    message: `${tech.username} 在选定期间无排班，建议安排工作`
                });
            } else if (workDays > analysis.totalDays * 0.8) {
                analysis.suggestions.push({
                    type: 'info',
                    technician: tech.username,
                    message: `${tech.username} 工作负荷较重（${workDays}天），注意劳逸结合`
                });
            }
        });

        res.json({
            success: true,
            data: analysis
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取优化建议失败',
            error: error.message
        });
    }
});

// 检查时间冲突
router.get('/check-conflict', async (req, res) => {
    try {
        const { technicianId, start, end, excludeId } = req.query;
        
        if (!technicianId || !start || !end) {
            return res.status(400).json({
                success: false,
                message: '请提供技师ID、开始时间和结束时间'
            });
        }

        const conflict = await Schedule.checkConflict(
            technicianId,
            new Date(start),
            new Date(end),
            excludeId
        );

        res.json({
            success: true,
            data: { hasConflict: conflict }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '检查时间冲突失败',
            error: error.message
        });
    }
});

module.exports = router;